-module(output_latex_sum).
-include("../measure_defs.hrl").
-export([format/2]).

-define(TABLE_WIDTH, 6).


print_error(#tail_data{mes_err1 = Err1, mes_err2 = Err2}) ->
    %io:format("print error:~p~n", [Err]),
    " & "++output_latex_common:float_to_latex(Err2)++
    " & "++output_latex_common:float_to_latex(Err1).

process_classes([#tail_data{} = T], N) when N =:= 0 ->
     print_error(T);
process_classes([#tail_data{} = T], N) when N > 0 ->
    " & \\multicolumn{"++integer_to_list(N*2)++"}{|c|}{n.a.}"
    ++print_error(T);
process_classes([#results{avg = Avg}|Classes], N) when N > 0 ->
    " & "++output_latex_common:float_to_latex(Avg)
    ++process_classes(Classes, N-1).

process_tail(L) ->
    #tail_data{alpha = Alpha, alpha0 = Alpha0, beta = Beta, reg_err = MaxErr, mes_err1 = Err1, avg = Avg} = lists:last(L),
    " & "++output_latex_common:float_to_latex(Avg)++
    case L of
    [#results{},#tail_data{}] ->
        " & \\multicolumn{6}{c|}{n.a.}";
    _ ->
        " & "++output_latex_common:float_to_latex(Alpha, 4 )
        ++" & "++output_latex_common:float_to_latex(Beta, 4)
        ++" & "++output_latex_common:float_to_latex( (MaxErr+Err1), 4 )
    end.
%    ++" & "++output_latex_common:float_to_latex(100*Alpha0)
%    ++" & "++output_latex_common:float_to_latex(MaxErr)
%    ++" & "++output_latex_common:float_to_latex(Err1)

process([], _) ->
    "";
process([Classes = [#results{name = Category} |_] | Categories ], Mode = sum) ->
    "\\quad "++Category
    ++process_tail(Classes)
    ++" \\\\ \n \\hline \n"
    ++process(Categories, Mode);
process([Classes = [#results{name = Category} |_] | Categories ], Mode = details) ->
    "\\quad "++Category
    ++process_classes(Classes, ?TABLE_WIDTH)
    ++" \\\\ \n \\hline \n"
    ++process(Categories, Mode).
    
format(#all_results{res_list = L, sys_name = SysName, sys_short_name = SysShortName}, Mode) ->
%    io:format("List=~p~n", [L]),
    Width = 
        case Mode of
        details -> 2*?TABLE_WIDTH+5;
        sum -> 9
        end,
            
    S =
        "\\multicolumn{"++integer_to_list(Width)++"}{|l|}{\\textbf{"++SysName++"}} "++
        " \\\\ \n"++
        "\\hline \n"++
        process(L, Mode),
    OutFile = SysShortName ++ "_"++atom_to_list(Mode)++".tex",
    file:write_file(OutFile, S).
